//
// Created by alexa on 5/13/2024.
//

#include "MainService.h"

#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

MainService::MainService() {
    soldiersService = new SoldiersService();
    crewsService = new CrewsService(soldiersService);
    soldiersService->setCrewsService(crewsService);
    missilesService = new MissilesService();
    unitsService = new UnitsService(crewsService, missilesService);
    missilesService->setUnitsService(unitsService);
    crewsService->setUnitsService(unitsService);
    battalionsService = new BattalionsService(unitsService);
    unitsService->setBattalionsService(battalionsService);
    string dataDirPath = loadConfigFromFile();
    setDefaultDataDirectory(dataDirPath);
}

void MainService::setDefaultDataDirectory(string path) const {
    if (path == ".") path = "data";
    saveConfigToFile(path);
    if (path == "") {
        soldiersService->repository.setFileSourcePath("");
        crewsService->repository.setFileSourcePath("");
        unitsService->repository.setFileSourcePath("");
        missilesService->repository.setFileSourcePath("");
        battalionsService->repository.setFileSourcePath("");
        return;
    }
    std::filesystem::create_directories(path);
    std::filesystem::path dirPath = path;
    soldiersService->repository.setFileSourcePath(dirPath.string() + "/soldiers.json");
    crewsService->repository.setFileSourcePath(dirPath.string() + "/crews.json");
    unitsService->repository.setFileSourcePath(dirPath.string() + "/units.json");
    missilesService->repository.setFileSourcePath(dirPath.string() + "/missiles.json");
    battalionsService->repository.setFileSourcePath(dirPath.string() + "/battalions.json");
}

string MainService::loadConfigFromFile() {
    try {
        ifstream file("cfg.json");
        json jobj = json::parse(file);
        file.close();
        return jobj.at("dataDirPath");
    } catch (std::exception &e) {
        saveConfigToFile("data");
        return ".";
    }
}

void MainService::saveConfigToFile(string dataDirPath) {
    ofstream file("cfg.json");
    json jobj = json::object();
    jobj["dataDirPath"] = dataDirPath;
    file << jobj.dump(4) << endl;
    file.close();
}

MainService::~MainService() {
    delete soldiersService;
    delete crewsService;
    delete unitsService;
    delete missilesService;
    delete battalionsService;
}
